var express = require('express')
const models = require("../../models");
const {success, error} = require("../../utils/message");
var router = express.Router()
const checkPermission = require('../../middlewares/check-permission')

// 通知列表
router.get('/', checkPermission(), async function (req, res, next) {
    let notices = await models.Notice.findAll({
        order: [
            ['createdAt', 'DESC'],
        ],
    })
    success(res, '查询成功', {notices})
})

// 新增通知
router.post('/', checkPermission(), async function (req, res, next) {
    const title = req.body.title

    if (!title) {
        return error(res, '请填写通知标题')
    }

    const noticeTitle = await models.Notice.findOne({where: {title: title}})
    if (noticeTitle) {
        return error(res, '标题已存在，请勿重复添加')
    }

    let notice = await models.Notice.create(req.body)
    success(res, '新增成功', {notice})
});

// 查询单条通知
router.get('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const notice = await models.Notice.findByPk(id)
    if (!notice) {
        return error(res, '当前通知不存在，无法修改')
    }

    success(res, '查询成功', {notice})
})

// 修改通知
router.put('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const title = req.body.title

    if (!title) {
        return error(res, '请填写标题')
    }

    const notice = await models.Notice.findByPk(id)
    if (!notice) {
        return error(res, '当前通知不存在，无法修改')
    }

    notice.update(req.body)
    success(res, '修改成功', {notice})
})

// 删除通知
router.delete('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const notice = await models.Notice.findOne({
        where: {id: id},
    })

    notice.destroy()
    success(res, '删除成功')
})
module.exports = router
